package org.chench.extra;

import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

/**
 * 使用Pull模式获取任务
 * @author chench9@lenovo.com
 * @desc org.chench.extra.TaskWorker
 * @date 3/20/19 7:11 PM
 */
public class TaskWorker {
    public static void main(String[] args) {
        try {
            startWorker();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void startWorker() throws InterruptedException {
        try (ZContext context = new ZContext()){
            // receiver
            ZMQ.Socket receiver = context.createSocket(SocketType.PULL);
            receiver.connect("tcp://localhost:5557");

            // sender
            ZMQ.Socket sender = context.createSocket(SocketType.PUSH);
            sender.connect("tcp://localhost:5558");

            // 循环接收任务
            while(!Thread.currentThread().isInterrupted()) {
                String string = new String(receiver.recv(0));
                long msec = Long.valueOf(string);

                System.out.flush();
                System.out.println(string + ".");

                // do worker
                Thread.sleep(msec);

                // send result to sinker
                sender.send(ZMQ.MESSAGE_SEPARATOR, 0);
            }
        }
    }
}
